package com.zzyl.nursing.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdcardUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.core.text.Convert;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.NursingTaskListDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.INursingTaskService;
import com.zzyl.nursing.vo.NursingTaskDetailVo;
import com.zzyl.system.mapper.SysUserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * 护理任务Service业务层处理
 *
 * @author alexis
 * @date 2024-11-17
 */
@Service
@Slf4j
public class NursingTaskServiceImpl extends ServiceImpl<NursingTaskMapper, NursingTask> implements INursingTaskService
{
    @Autowired
    private NursingTaskMapper nursingTaskMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private NursingProjectMapper nursingProjectMapper;
    @Autowired
    private NursingProjectPlanMapper nursingProjectPlanMapper;
    @Autowired
    private NursingLevelMapper nursingLevelMapper;

    /**
     * 查询护理任务
     *
     * @param id 护理任务主键
     * @return 护理任务
     */
    @Override
    public NursingTaskDetailVo selectNursingTaskById(Long id) {

        NursingTaskDetailVo nursingTaskDetailVo = new NursingTaskDetailVo();
        //根据id查询护理任务表MybatisPlus查询,返回NursingTask
        NursingTask nursingTask = nursingTaskMapper.selectById(id);

        //处理老人的年龄和性别
        Elder elder = elderMapper.selectById(nursingTask.getElderId());



        //护理等级名称

        //根据护理项目id查询护理项目计划表，返回并封装在NursingProjectPlan对象中
        LambdaQueryWrapper<NursingProjectPlan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NursingProjectPlan::getProjectId, nursingTask.getProjectId())
                .orderByDesc(NursingProjectPlan::getCreateTime);
        List<NursingProjectPlan> nursingProjectPlans  = nursingProjectPlanMapper.selectList(queryWrapper);
        NursingProjectPlan nursingProjectPlan = nursingProjectPlans.get(0);

        LambdaQueryWrapper<NursingLevel> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(NursingLevel::getLplanId, nursingProjectPlan.getPlanId())
                .orderByDesc(NursingLevel::getCreateTime);
        NursingLevel nursingLevel = nursingLevelMapper.selectOne(queryWrapper1);

        //护理员姓名列表

        //数据库获取的string类型的id转为int类型的集合
        Integer[] intArray = Convert.toIntArray(",", nursingTask.getNursingId());
        List<Integer> nursingids = Arrays.asList(intArray);
        //根据nursingId的集合通过Mybits查询nursingName集合放入到NursingTask中
        nursingTask.setNursingName(sysUserMapper.selectUserByIds(nursingids));

        //获取当前登录用户名
        String username = SecurityUtils.getUsername();

        //规整
        BeanUtil.copyProperties(nursingTask, nursingTaskDetailVo);
        nursingTaskDetailVo.setAge(IdcardUtil.getAgeByIdCard(elder.getIdCardNo()));
        String sex ="";
        if (elder.getSex()==1) {
            sex = "男";
        }else {
            sex = "女";
        }
        nursingTaskDetailVo.setSex(sex);
        nursingTaskDetailVo.setNursingLevelName(nursingLevel.getName());
        nursingTaskDetailVo.setUpdater( username);

        return nursingTaskDetailVo;
    }

    /**
     * 查询护理任务列表
     *
     * @param nursingTaskdto 护理任务
     * @return 护理任务
     */
    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public List<NursingTask> selectNursingTaskList(NursingTaskListDto nursingTaskdto) {

        //传入的护理员id由int转为String类型

        //查询条件

        LambdaQueryWrapper<NursingTask> lambdaQuery = new LambdaQueryWrapper<>();

        lambdaQuery.like(nursingTaskdto.getElderName() != null && nursingTaskdto.getElderName() != "", NursingTask::getElderName, nursingTaskdto.getElderName())
                .like(nursingTaskdto.getNurseId() != null, NursingTask::getNursingId, String.valueOf(nursingTaskdto.getNurseId()))
                .eq(nursingTaskdto.getProjectId() != null, NursingTask::getProjectId, nursingTaskdto.getProjectId())
                .between(nursingTaskdto.getStartTime() != null && nursingTaskdto.getEndTime() != null, NursingTask::getEstimatedServerTime, nursingTaskdto.getStartTime(), nursingTaskdto.getEndTime());

        //查询MybatisPlus查询
        List<NursingTask> list = list(lambdaQuery);

        //根据nursingId查询nursingName
        list.forEach(nursingTask -> {
            //数据库获取的string类型的id转为int类型的集合
            Integer[] intArray = Convert.toIntArray(",", nursingTask.getNursingId());
            List<Integer> nursingids = Arrays.asList(intArray);
            //根据nursingId的集合通过Mybits查询nursingName集合放入到NursingTask中
            nursingTask.setNursingName(sysUserMapper.selectUserByIds(nursingids));
        });

        return list;
    }

    /**
     * 新增护理任务
     *
     * @param nursingTask 护理任务
     * @return 结果
     */
    @Override
    public int insertNursingTask(NursingTask nursingTask) {
        return save(nursingTask) ? 1 : 0;
    }

    /**
     * 修改护理任务
     *
     * @param nursingTask 护理任务
     * @return 结果
     */
    @Override
    public int updateNursingTask(NursingTask nursingTask) {
        return updateById(nursingTask) ? 1 : 0;
    }

    /**
     * 批量删除护理任务
     *
     * @param ids 需要删除的护理任务主键
     * @return 结果
     */
    @Override
    public int deleteNursingTaskByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除护理任务信息
     *
     * @param id 护理任务主键
     * @return 结果
     */
    @Override
    public int deleteNursingTaskById(Long id) {
        return removeById(id) ? 1 : 0;
    }





    //上述为代码生成，以下为自定义代码
    //----------------------------------------------//


    @Override
    public void cancel(Long taskId, String cancelReason) {

        log.info("取消任务：{}，取消原因：{}", taskId, cancelReason);
        //使用LambdaUpdateWrapper,设置更新条件，根据taskId，更新cancelReason字段，和status字段
        LambdaQueryWrapper<NursingTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NursingTask::getId, taskId);
        //使用builder方法，设置更新字段
        NursingTask nursingTask = NursingTask.builder()
                .cancelReason(cancelReason)
                .status(3)
                .build();
        update(nursingTask, queryWrapper);

    }

    /**
     * 执行任务
     * @param taskId
     * @param estimatedServerTime
     * @param mark
     * @param taskImage
     */
    @Override
    public void doTask(Long taskId, String estimatedServerTime, String mark, String taskImage) {
        log.info("执行任务");
        LambdaQueryWrapper<NursingTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NursingTask::getId, taskId);
        //格式化 时间
        // 假设 estimatedServerTime 的格式是 "yyyy-MM-dd HH:mm:ss"
        String pattern = "yyyy-MM-dd HH:mm:ss";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);

        LocalDateTime estimatedTime = LocalDateTime.parse(estimatedServerTime, formatter);
        NursingTask nursingTask = NursingTask.builder()
                .estimatedServerTime(estimatedTime)
                .mark(mark)
                .taskImage(taskImage)
                .status(2)
                .build();
        update(nursingTask, queryWrapper);

    }
    /**
     * 更新任务时间
     * @param taskId
     * @param estimatedServerTime
     */
    @Override
    public void updateTime(Long taskId, String estimatedServerTime) {
        log.info("更新任务时间");
        LambdaQueryWrapper<NursingTask> queryWrapper = new LambdaQueryWrapper<>();
        LocalDateTime localDateTime = DateUtil.parse(estimatedServerTime, "yyyy-MM-dd HH:mm:ss").toLocalDateTime();
        queryWrapper.eq(NursingTask::getId, taskId);
        NursingTask nursingTask = NursingTask.builder()
                .estimatedServerTime(localDateTime)
                .status(1)
                .build();
        update(nursingTask, queryWrapper);

    }

}
